<template>
  <div class="map">
    <!-- <el-button type="primary" @click="MultipleMark">显示多个标记</el-button>
	  <el-button type="primary" @click="text">图文标记</el-button>
	  <el-button type="primary" @click="initMap">图文标记</el-button> -->
    <!-- 地图容器 -->
    <el-dialog
      title="请选择地址"
      :visible="dialogVisible"
      :before-close="handleClose"
    >
      <div id="mapContainer" style="width: 100%; height: 500px"></div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose()">取 消</el-button>
        <el-button type="primary" @click="handleClose('sure')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import qq from 'qq';
  import { jsonp } from 'vue-jsonp';
  import axios from 'axios';
  export default {
    props: {
      dialog: Boolean
    },
    data() {
      return {
        map: null,
        longitude: null, //经度
        latitude: null,
        marker: null, //纬度
        markersArray: [],
        dialogVisible: false,
        location: null,
        address: null
      };
    },

    created() {},
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {
      this.longitude = localStorage.getItem('longitude')
        ? localStorage.getItem('longitude')
        : 26.254009;
      this.latitude = localStorage.getItem('latitude')
        ? localStorage.getItem('latitude')
        : 111.611786;
      // this.getUserLocation();
    },
    watch: {
      dialog(visible) {
        this.dialogVisible = visible;
        setTimeout(() => {
          this.initMap();
        });
      }
    },
    methods: {
      handleClose(sure) {
        if (!this.address) {
          this.address = '湖南省永州市冷水滩区冷水滩区岚角山街道黄泥塘';
        }
        if (sure) {
          this.$emit('address', this.address);
          this.$emit('location', this.location);
        }
        console.log('关闭');
        this.$emit('update:dialog', false);
      },
      getUserLocation(latitude, longitude) {
        let url = 'https://apis.map.qq.com/ws/geocoder/v1/?address=';
        this.$jsonp(url, {
          key: 'D4FBZ-TGQ6J-I2HFZ-FVHIT-VLIH7-Z6BZS',
          location: `${longitude},${latitude}`,
          output: 'jsonp'
        })
          .then((res) => {
            console.log(res);
            console.log(res);
            this.latitude = res.result.location.lng;
            this.longitude = res.result.location.lat;
            // 存缓存
            localStorage.setItem('latitude', this.latitude);
            localStorage.setItem('longitude', this.longitude);

            console.log('res.result.location.lat: ', res.result.location.lat);
            console.log('res.result.location.lng: ', res.result.location.lng);
            //   alert('经度:' + this.longitude + ',' + '纬度:' + this.latitude);
            //   alert(
            //     `${res.result.address}${res.result.formatted_addresses.rough}`
            //   );
            this.location = {
              longitude: this.longitude,
              latitude: this.latitude
            };
            this.address = `${res.result.address}${res.result.formatted_addresses.rough}`;

            // this.$wx.openLocation({
            //   latitude: latitude,
            //   longitude: longitude,
            //   name: this.address, // 位置名
            //   address: this.address, // 地址详情说明
            //   scale: 15, // 地图缩放级别,整型值,范围从1~28。默认为最大
            //   infoUrl: '' // 在查看位置界面底部显示的超链接,可点击跳转
            // });
          })
          .catch((err) => {
            console.log(err);
          });
      },
      initMap() {
        //步骤：定义map变量 调用 qq.maps.Map() 构造函数   获取地图显示容器
        //设置地图中心点
        var myLatlng = new qq.maps.LatLng(this.longitude, this.latitude);
        console.log(myLatlng);
        //定义工厂模式函数
        var myOptions = {
          zoom: 8, //设置地图缩放级别
          center: myLatlng, //设置中心点样式
          mapTypeId: qq.maps.MapTypeId.ROADMAP //设置地图样式详情参见MapType
        };
        //获取dom元素添加地图信息
        this.map = new qq.maps.Map(
          document.getElementById('mapContainer'),
          myOptions
        );
        this.marker = new qq.maps.Marker({
          position: myLatlng,
          map: this.map
        });
        this.markersArray.push(this.marker);
        //给地图添加点击事件
        //并获取鼠标点击的经纬度
        qq.maps.event.addListener(this.map, 'click', (event) => {
          this.longitude = event.latLng.getLat();
          this.latitude = event.latLng.getLng();
          this.mark();

          this.getUserLocation(this.latitude, this.longitude);
        });

        // 标记
        this.mark();
      },

      // 标记
      mark() {
        for (var i = 0; i < this.markersArray.length; i++) {
          this.markersArray[i].setMap(null);
        }
        this.markersArray = []; // 清空存储标记的数组
        var myLatlng = new qq.maps.LatLng(this.longitude, this.latitude);
        this.marker = new qq.maps.Marker({
          position: myLatlng,
          map: this.map
        });
        this.markersArray.push(this.marker);
        //给定位的位置添加文本标注
        // this.marker = new qq.maps.Label({
        //   position: myLatlng,
        //   map: this.map,
        //   content: '这是我当前的位置，偏差有点大，哈哈'
        // });
      },

      // 显示多个标记
      MultipleMark() {
        var lang = [
          // 再加两个坐标(坐标乱写的)
          { id: 2, longitude: 39.994104, latitude: 116.287503 },
          { id: 3, longitude: 39.954104, latitude: 116.357503 }
        ];
        this.mark(lang);
      },

      // 图文标记
      text() {
        var lang = [
          // 再加两个坐标(坐标乱写的)
          {
            id: 2,
            longitude: 39.994104,
            latitude: 116.287503,
            text: '标记点一'
          },
          {
            id: 3,
            longitude: 39.954104,
            latitude: 116.357503,
            text: '标记点二'
          }
        ];
        this.mark(lang);
      }
    }
  };
</script>

<style></style>
